package com.wdm.diffutils.util;

import com.wdm.diffutils.marker.Aggregate;

import java.io.*;

/**
 * Description:
 * 深度拷贝工具类 给聚合打快照
 * @author wudaiming
 * @date 2023/10/26 12:38
 */
public class SnapshotUtils {
    
    /**
     * Creates a deep copy of the given aggregate object.
     *
     * @param aggregate the aggregate object to be copied
     * @param <T>       the type of the aggregate object
     * @return the deep copied aggregate object
     * @throws IOException            if an I/O error occurs
     * @throws ClassNotFoundException if a class is not found during deserialization
     */
    @SuppressWarnings("unchecked")
    public static <T extends Aggregate<?> & Serializable> T snapshot(T aggregate) throws IOException, ClassNotFoundException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(aggregate);
        
        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bis);
        return (T) ois.readObject();
    }
}
